import React, { Component, PropTypes } from 'react';
import { Upload, Icon, Modal, message } from 'antd';
import Styles from './imgUpload.less';

class ImgUpload extends React.Component {
  state = {
    fileList: []
  }

  handleChange = ({ fileList }) => {
    const _this = this;
    const { onComplete, limit } = this.props;

    this.setState({ fileList });

    fileList.filter((file) => {
      if (file.response) {
        if (file.response.success) {
          if (limit) {
            const image = new Image();
            image.src = file.response.data;
            image.onload = function () {
              if (image.width === limit.width && image.height === limit.height) {
                message.success('图片上传成功', 3);
                onComplete(file.response.data);
                return;
              }
              _this.setState({fileList: []})
              message.error(`图片上传尺寸不对，要求尺寸${limit.width}*${limit.height}`, 3);
            }
          } else {
            onComplete(file.response.data);
          }
        } else {
          message.error(file.response.msg);
        }
      }
    })
  }

  beforeUpload = (file) => {
    const { maxMass } = this.props;
    console.log(maxMass);
    if (maxMass && maxMass.kg) {
      if (file && file.size > maxMass.kg) {
        message.error('图片质量过大，应该小于1M');
        return false;
      }
    } 
  }

  render() {
    const { fileList } = this.state;
    const uploadButton = this.props.initUrl ? (
      <div><img src={this.props.initUrl} /></div>
      ) : (
      <div className="uploadPlus">
        <Icon type="plus" />
        <div className="ant-upload-text">{this.props.uploadText ? this.props.uploadText : '点击上传'}</div>
      </div>
    )

    return (
      <div className={this.props.initUrl ? Styles.haveImg : null}>
        <Upload
          listType="picture-card"
          action="/api/public/image/upload"
          fileList={fileList}
          onChange={this.handleChange}
          beforeUpload={this.beforeUpload}
        >
          {fileList.length > 0 ? null : uploadButton}
        </Upload>
      </div>
    );
  }
}


export default ImgUpload;